import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

import '../../../hj_model/video_model.dart';
import '../search_page/widget/search_user_cell.dart';

class FollowUserListView extends StatefulWidget {
  const FollowUserListView({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FollowUserListViewState();
  }
}

class _FollowUserListViewState extends State<FollowUserListView> {
  RefreshController? controller;
  List<VideoModel>? dataSource;
  int pageNumber = 1;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadData();
    });
  }

  void _loadData({int page = 1, int size = 10}) async {
    try {
      dataSource ??= [];
      controller?.loadComplete();
    } catch (e) {
      controller?.loadComplete();
      debugLog(e);
    }
    dataSource ??= [];
    controller?.refreshCompleted();
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (dataSource == null) {
      return LoadingCenterWidget();
    } else if (dataSource!.isEmpty) {
      return CErrorWidget(
        retryOnTap: () {
          dataSource = null;
          setState(() {});
          _loadData();
        },
      );
    } else {
      return pullYsRefresh(
        onInit: (ctr) => controller = ctr,
        onRefresh: (ctr) => _loadData(),
        onLoading: (ctr) => _loadData(page: pageNumber + 1),
        child: GridView.builder(
          padding: EdgeInsets.symmetric(horizontal: 12),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 12,
            crossAxisSpacing: 8,
            childAspectRatio: 168 / 142,
          ),
          itemCount: dataSource?.length ?? 0,
          itemBuilder: (context, index) {
            VideoModel model = dataSource![index];
            return SearchUserCell();
          },
        ),
      );
    }
  }
}
